package com.ruoyi.stream.framework.model.request;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.stream.framework.core.DefaultSingleIOTaskGroupFactory;
import com.ruoyi.stream.framework.core.protocol.SKAProtocolContext;
import com.ruoyi.stream.framework.core.protocol.StreamAliveRequest;
import com.ruoyi.stream.framework.core.protocol.StreamAliveResponse;
import com.ruoyi.stream.framework.core.workDomain.SingleIOTask;
import com.ruoyi.stream.framework.enums.IOTaskConfigBuilderEnum;
import com.ruoyi.stream.framework.enums.SKAResponseOption;
import com.ruoyi.stream.framework.model.configBuilder.IOTaskConfigBuilderFactory;
import com.ruoyi.stream.framework.model.configBuilder.single.SingleIOTaskConfig;
import com.ruoyi.stream.framework.model.configBuilder.single.SingleIOTaskConfigBuilder;

import java.io.InputStream;

public class SingleTaskProcessor extends RequestProcessor{

    private static DefaultSingleIOTaskGroupFactory defaultIOTaskGroupFactory = SpringUtils.getBean(DefaultSingleIOTaskGroupFactory.class);

    @Override
    public void handleRequestResource(StreamAliveResponse response) {
        SKAProtocolContext context = this.getContext();
        StreamAliveRequest onRequest = context.getOnRequest();
        Object o = this.getHandler().onRequest(onRequest, response);
        response.setBody(o);
        getCtx().writeAndFlush(response);
    }

    @Override
    public void handleReady(StreamAliveResponse response) {
        SKAProtocolContext context = getContext();
        SingleIOTaskConfigBuilder builder = IOTaskConfigBuilderFactory.getBuilder(IOTaskConfigBuilderEnum.SINGLE_TASK);
        boolean b = getHandler().onReady(context.getReadyAccept(), context, builder);
        if (!b){
            response.setResponseOption(SKAResponseOption.REFUSE);
            handleRefuse(context.getReadyAccept(),response);
            getCtx().writeAndFlush(response);
            return;
        }
        InputStream start = getHandler().start(context.getReadyAccept(), context);
        SingleIOTaskConfig build = builder.build();
        SingleIOTask singleIOTask = new SingleIOTask(start,build.getReadCacheLength(),build.getCancelBehavior()
        ,build.getProductBehavior(),build.getPauseBehavior(),build.getConsumeIO(),this.getCtx().channel());
        singleIOTask.setGroup(defaultIOTaskGroupFactory.getGroup());
    }



    @Override
    public void handleRefuse(StreamAliveRequest request,StreamAliveResponse response) {
       getHandler().onRefuse(request,response);
    }
}
